<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="kYQuniuaRZuL9fq0DATfL7extAwcqWG6Ki286ZMcpak">
  <meta name="baidu-site-verification" content="code-MRqS7DOO9x">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha256-DfWjNxDkM94fVBWx1H5BMMp0Zq7luBlV8QRcSES7s+0=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blogwxb.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.11.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":true,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"gitalk","storage":true,"lazyload":false,"nav":null,"activeClass":"gitalk"},"stickytabs":false,"motion":{"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="一、什么是Generator函数Generator 函数是 ES6 提供的一种异步编程解决方案，语法行为与传统函数完全不同。由于JavaScript是单线程语言，因此传统的函数程序开始执行直到运行结束才会停止，在此期间是不会被其他代码片段打断的。但是generator函数能够利用它独有的特性yield表达式去控制程序的运行的状态，暂停还是继续。 Generator和普通函数的区别  写法的不同，G">
<meta property="og:type" content="article">
<meta property="og:title" content="你不知道的Generator函数">
<meta property="og:url" content="https://blogwxb.cn/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/index.html">
<meta property="og:site_name" content="会飞的猪9527">
<meta property="og:description" content="一、什么是Generator函数Generator 函数是 ES6 提供的一种异步编程解决方案，语法行为与传统函数完全不同。由于JavaScript是单线程语言，因此传统的函数程序开始执行直到运行结束才会停止，在此期间是不会被其他代码片段打断的。但是generator函数能够利用它独有的特性yield表达式去控制程序的运行的状态，暂停还是继续。 Generator和普通函数的区别  写法的不同，G">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blogwxb.cn/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/0.png">
<meta property="og:image" content="https://blogwxb.cn/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/1.png">
<meta property="article:published_time" content="2021-03-12T02:55:44.000Z">
<meta property="article:modified_time" content="2022-10-07T15:14:03.001Z">
<meta property="article:author" content="wxb">
<meta property="article:tag" content="ES6">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blogwxb.cn/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/0.png">


<link rel="canonical" href="https://blogwxb.cn/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://blogwxb.cn/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/","path":"你不知道的Generator函数/","title":"你不知道的Generator函数"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>你不知道的Generator函数 | 会飞的猪9527</title>
  





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <!-- Google Analytics -->
  <script>
  window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
  ga('create', 'UA-XXXXX-Y', 'auto');
  ga('send', 'pageview');
  </script>
  <script async src='https://www.google-analytics.com/analytics.js'></script>
  <!-- End Google Analytics -->

  <!-- Baidu Analytics -->
  <script async src = 'https://zz.bdstatic.com/linksubmit/push.js'></script>
  <!-- End Baidu Analytics -->

<link rel="alternate" href="/atom.xml" title="会飞的猪9527" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">会飞的猪9527</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">32</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">5</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">91</span></a></li><li class="menu-item menu-item-commonweal"><a href="/404" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E4%BB%80%E4%B9%88%E6%98%AFGenerator%E5%87%BD%E6%95%B0"><span class="nav-number">1.</span> <span class="nav-text">一、什么是Generator函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81next%E6%96%B9%E6%B3%95"><span class="nav-number">2.</span> <span class="nav-text">二、next方法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81iterable"><span class="nav-number">3.</span> <span class="nav-text">三、iterable</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9B%9B%E3%80%81Generator%E5%87%BD%E6%95%B0%E5%9C%A8%E5%BC%82%E6%AD%A5%E4%B8%AD%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">4.</span> <span class="nav-text">四、Generator函数在异步中的使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%94%E3%80%81Generator%E5%87%BD%E6%95%B0%E5%92%8CPromise%E7%BB%93%E5%90%88"><span class="nav-number">5.</span> <span class="nav-text">五、Generator函数和Promise结合</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%AD%E3%80%81async%E3%80%81await%E5%92%8CGenerator%E5%87%BD%E6%95%B0%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">6.</span> <span class="nav-text">六、async、await和Generator函数的区别</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="wxb"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">wxb</p>
  <div class="site-description" itemprop="description">主要是分享自己在Web前端的一些入的坑，脱的坑的经历，也会是分享一些Node后端的知识。</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">91</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">32</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/dearDreamWeb" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;dearDreamWeb" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>


  <div class="links-of-blogroll site-overview-item animated">
    <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
      推荐
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.ruanyifeng.com/blog/" title="https:&#x2F;&#x2F;www.ruanyifeng.com&#x2F;blog&#x2F;" rel="noopener" target="_blank">阮一峰的网络日志</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://nav.blogwxb.cn/" title="https:&#x2F;&#x2F;nav.blogwxb.cn&#x2F;" rel="noopener" target="_blank">轩辕导航</a>
        </li>
    </ul>
  </div>

        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/dearDreamWeb" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://blogwxb.cn/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="wxb">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="会飞的猪9527">
      <meta itemprop="description" content="主要是分享自己在Web前端的一些入的坑，脱的坑的经历，也会是分享一些Node后端的知识。">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="你不知道的Generator函数 | 会飞的猪9527">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          你不知道的Generator函数
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-03-12 10:55:44" itemprop="dateCreated datePublished" datetime="2021-03-12T10:55:44+08:00">2021-03-12</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2022-10-07 23:14:03" itemprop="dateModified" datetime="2022-10-07T23:14:03+08:00">2022-10-07</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">前端</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <!-- <span id="busuanzi_value_page_pv"></span> -->
      <span id="views_text"></span>
    </span>
</div>


        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="一、什么是Generator函数"><a href="#一、什么是Generator函数" class="headerlink" title="一、什么是Generator函数"></a>一、什么是Generator函数</h1><p>Generator 函数是 ES6 提供的一种<code>异步编程解决方案</code>，语法行为与传统函数完全不同。<br>由于JavaScript是单线程语言，因此传统的函数<code>程序开始执行直到运行结束</code>才会停止，在此期间是不会被其他代码片段打断的。但是generator函数能够利用它独有的特性<code>yield表达式</code>去控制程序的运行的状态，暂停还是继续。</p>
<p><strong>Generator和普通函数的区别</strong></p>
<ol>
<li>写法的不同，Generator函数function后要加上<code>星号</code>，Generator函数是可以<code>暂停执行</code>的。<br>例子：<span id="more"></span>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 普通函数写法</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">fn</span>(<span class="params"></span>)&#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Generator函数的写法</span></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">generator</span>(<span class="params"></span>)&#123;&#125;</span><br></pre></td></tr></table></figure></li>
<li>Generator函数体内使用<code>yield</code>语句，可以定义不同的内部状态；状态其实就是数据。使用yield进行暂停操作，和async await异步处理中的<code>await</code>效果一样。</li>
</ol>
<h1 id="二、next方法"><a href="#二、next方法" class="headerlink" title="二、next方法"></a>二、next方法</h1><p>next的特性  </p>
<ul>
<li>next方法是通过配合yield，去为了将generator函数去进行迭代，通过next方法去获取yield表达式后面的数据。  </li>
<li>每次程序运行到yield表达式，就会将程序的状态设为<code>暂停</code>，也就是<code>暂时停止执行后面的一系列操作</code>，并将在该yield表达式后面的值，作为返回的对象数据中的<code>value</code>字段的属性值；  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">generator</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> gen = <span class="title function_">generator</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(gen.<span class="title function_">next</span>());    <span class="comment">// &#123; value: &#x27;a&#x27;, done: false &#125;</span></span><br></pre></td></tr></table></figure></li>
<li>next方法所返回的数据是一个对象，对象里面有两个属性，一个是<code>value</code>，一个是<code>done</code>。<br><code>value</code>代表<code>yield后面表达式的值</code>，<code>done</code>代表<code>是否遍历结束</code>，true表示遍历结束，false表示未结束。    <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">generator</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;b&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> gen = <span class="title function_">generator</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(gen.<span class="title function_">next</span>());    <span class="comment">// &#123; value: &#x27;a&#x27;, done: false &#125;</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(gen.<span class="title function_">next</span>());    <span class="comment">// &#123; value: &#x27;b&#x27;, done: false &#125;</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(gen.<span class="title function_">next</span>());    <span class="comment">// &#123; value: undefined, done: true &#125;</span></span><br></pre></td></tr></table></figure></li>
<li>下一次调用next方法时，再继续往下执行，直到遇到<code>下一个yield表达式</code>或者将generator函数执行结束；</li>
<li>没有再遇到新的yield表达式，就<code>一直运行到函数结束</code>，如果遇到return会将<code>return语句</code>后面的表达式的<code>值</code>，作为返回的对象的<code>value属性值</code>，效果和yield是一样的；  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">generator</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="string">&#x27;a&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;b&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> gen = <span class="title function_">generator</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(gen.<span class="title function_">next</span>());    <span class="comment">// &#123; value: &#x27;a&#x27;, done: false &#125;</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(gen.<span class="title function_">next</span>());    <span class="comment">// &#123; value: &#x27;b&#x27;, done: true &#125;</span></span><br></pre></td></tr></table></figure></li>
<li>如果该函数没有return语句或者yield表达式，则返回的对象的value属性值为undefined；  <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">generator</span>(<span class="params"></span>) &#123;&#125;</span><br><span class="line"><span class="keyword">let</span> gen = <span class="title function_">generator</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(gen.<span class="title function_">next</span>());    <span class="comment">// &#123; value: undefined, done: true &#125;</span></span><br></pre></td></tr></table></figure></li>
<li>一般情况下，使用next方法的次数要比yield表达式多一个，因为next是遇到yield表达式部分去停止的，这个停止是在<code>语句中间终止</code>的，也就是包含该yield表达式的代码片段。想要执行完该代码片段必须要在调用一次next方法才能更将上次yield表达式所出的代码片段执行完。</li>
</ul>
<p>下面的例子就有点复杂了，但要记住上面的next的特性就好理解一些</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">foo</span>(<span class="params">x</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> y = <span class="number">2</span> * (<span class="keyword">yield</span> (x + <span class="number">1</span>));</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(y);</span><br><span class="line">    <span class="keyword">var</span> z = <span class="keyword">yield</span> (y / <span class="number">3</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(z);</span><br><span class="line">    <span class="keyword">yield</span> (x + y + z);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> a = <span class="title function_">foo</span>(<span class="number">5</span>);</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(a.<span class="title function_">next</span>());</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    第一次next()结果</span></span><br><span class="line"><span class="comment">    &#123; value: 6, done: false &#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(a.<span class="title function_">next</span>());</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    第二次next()结果</span></span><br><span class="line"><span class="comment">    NaN</span></span><br><span class="line"><span class="comment">    &#123; value: NaN, done: false &#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(a.<span class="title function_">next</span>());</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    第三次next()结果</span></span><br><span class="line"><span class="comment">    undefined</span></span><br><span class="line"><span class="comment">    &#123; value: NaN, done: false &#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>第一次的next()的结果很好理解<br>第二次的next()就有点魔幻了，下面好好解释一下：  </p>
<ul>
<li>y为什么成了NaN？<br>因为<code>y=2 * undefined</code>。  </li>
<li>但为什么第二次执行next()，yield(x+1)变成了undefined？<br>因为第一次只是执行到<code>yield(x+1)</code>就停止了，只是把x+1的结果返回给next了，并不知道yield(x+1)的结果是多少，因为<code>next()是遇到yield表达式会执行完就停止</code>，所以第二次执行next()的时候，根本就不知道第一次的next()的执行结果是什么，因为<code>第一次没有执行到给y赋值的时候</code>，所以就变成了<code>var y = 2 * undefined</code>了。<br>同理，第三次next()的执行结果是因为第二次next()只是执行到了yield(y&#x2F;3)就停止了，所以第三次的next()执行结果就为5+NaN+undefined，结果为NaN</li>
</ul>
<p><strong>next的参数</strong><br>next方法可以带一个参数，该<code>参数会成为上一个yield的返回值，并从上一次yield开始，直到下一个yield停止</code>。<br>例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">foo</span>(<span class="params">x</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> y = <span class="number">2</span> * (<span class="keyword">yield</span> (x + <span class="number">1</span>));</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(y);</span><br><span class="line">    <span class="keyword">var</span> z = <span class="keyword">yield</span> (y / <span class="number">3</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(z);</span><br><span class="line">    <span class="keyword">yield</span> (x + y + z);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> a = <span class="title function_">foo</span>(<span class="number">5</span>);</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(a.<span class="title function_">next</span>());</span><br><span class="line"><span class="comment">// &#123; value: 6, done: false &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(a.<span class="title function_">next</span>(<span class="number">12</span>));</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    24</span></span><br><span class="line"><span class="comment">    &#123; value: 8, done: false &#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(a.<span class="title function_">next</span>(<span class="number">13</span>));</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">    13</span></span><br><span class="line"><span class="comment">    &#123; value: 42, done: false &#125;</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>第一次next()的value是<code>5+1=6</code><br>第二次next()的value为8是因为next()的有参数，参数12变成foo函数中的上一次yield的返回值，也就是说<code>var y = 2 * 12;</code>，然后到yield(y&#x2F;3)执行完停止，所以value为8<br>第三次next()的value为42因为next()有参数，上一次的yield开始，变成了<code>var z = 13</code>,到yield(x+y+z)结束，所以value等于<code>x+y+z = 5+24+13 = 42</code></p>
<h1 id="三、iterable"><a href="#三、iterable" class="headerlink" title="三、iterable"></a>三、iterable</h1><p>iterable意为可迭代的，是ES6引入一个新类型，可以通过<code>for...of</code>来循环遍历，如<code>Array</code>、<code>Set</code>、<code>Map</code>都是属于iterable类型。Generator函数<code>运行时</code>返回一个iterable类型的迭代器。<br>下面是浏览器控制台上Set和Generator函数运行时原型上截图<br><img data-src="/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/0.png" alt="Set"><br><img data-src="/%E4%BD%A0%E4%B8%8D%E7%9F%A5%E9%81%93%E7%9A%84Generator%E5%87%BD%E6%95%B0/1.png" alt="Generator"><br><code>for...of循环是会寻找并调用目标的Symbol.iterator函数来构建一个迭代器。</code><br>例子：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span>* <span class="title function_">gen</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">2</span>;</span><br><span class="line">    <span class="keyword">yield</span> <span class="number">3</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> val <span class="keyword">of</span> <span class="title function_">gen</span>())&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(val);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 1</span></span><br><span class="line"><span class="comment">// 2</span></span><br><span class="line"><span class="comment">// 3</span></span><br></pre></td></tr></table></figure>
<p>注意：generator函数gen不是迭代器，gen()会产生一个迭代器。</p>
<h1 id="四、Generator函数在异步中的使用"><a href="#四、Generator函数在异步中的使用" class="headerlink" title="四、Generator函数在异步中的使用"></a>四、Generator函数在异步中的使用</h1><p>常用异步场景是向服务器发送请求。先从ajax使用说起，在ajax异步请求中是通过回调去接收返回数据，这就容易造成经常听说的<code>回调地狱</code>。<br>ajax正常的场景：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">request</span>(<span class="params">callback</span>)&#123;</span><br><span class="line">    <span class="title function_">ajax</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>,callback)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">request</span>(<span class="keyword">function</span>(<span class="params">err,data</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(!err)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>总所周知，一旦request这种请求函数多起来就很容易造成回调地狱这种局面，我们耳熟能详的解决方案是<code>async、await搭配promise</code>的解决方案，generator函数也是能达到同样的效果。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">request</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="title function_">ajax</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>,<span class="keyword">function</span>(<span class="params">err,data</span>)&#123;</span><br><span class="line">        <span class="keyword">if</span>(!err)&#123;</span><br><span class="line">            <span class="comment">// 将yield结果data返回，让res接收到data数据</span></span><br><span class="line">            g.<span class="title function_">next</span>(data);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">gen</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="comment">// 获取请求结果</span></span><br><span class="line">    <span class="keyword">let</span> res = <span class="keyword">yield</span> <span class="title function_">request</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">let</span> g = <span class="title function_">gen</span>();</span><br><span class="line">g.<span class="title function_">next</span>(); <span class="comment">// 开始运行</span></span><br></pre></td></tr></table></figure>
<p><strong>注意：</strong> 第一次g.next()仅仅是启动gen函数，运行到ajax中的<code>yield request()</code>停止，然后调用request函数去通过ajax发送请求，此时<code>res</code>还不知道yield的结果，通过调用<code>g.next(data)</code>将yield结果返回给res。  </p>
<h1 id="五、Generator函数和Promise结合"><a href="#五、Generator函数和Promise结合" class="headerlink" title="五、Generator函数和Promise结合"></a>五、Generator函数和Promise结合</h1><p>上诉的发送请求是ajax，如今常用的发送请求的方式基本都是基于<code>Promise</code>的，其中常用的是<a target="_blank" rel="noopener" href="https://axios-http.com/">axios</a>。<br>Axios搭配Generator函数基础用法：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">request</span>(<span class="params"></span>)&#123;</span><br><span class="line">   <span class="keyword">return</span> axios.<span class="title function_">get</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">getData</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="keyword">const</span> res = <span class="keyword">yield</span> <span class="title function_">request</span>()</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> g = <span class="title function_">getData</span>();</span><br><span class="line"><span class="keyword">const</span> p1 = g.<span class="title function_">next</span>().<span class="property">value</span></span><br><span class="line">p1.<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">data</span>)&#123;</span><br><span class="line">        g.<span class="title function_">next</span>(data); <span class="comment">// 将request请求返回的数据给yield</span></span><br><span class="line">    &#125;).<span class="title function_">catch</span>(<span class="keyword">function</span>(<span class="params">err</span>)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;)</span><br></pre></td></tr></table></figure>
<p>通过第一次<code>g.next()</code>将value值，也就是promise返回给<code>p1</code>，让p1通过<code>then</code>获取返回数据，然后再<code>yield</code>给getData函数中的<code>res赋值返回数据</code>。 </p>
<blockquote>
<p>这时候就会有个疑问：<br>看起来Generator函数配合Promise也没节省什么操作？  </p>
</blockquote>
<p>一旦请求躲起来就要一直next调用，一直手动迭代，所以不会节省什么效率，那么把Generator函数封装成可以一直把yield迭代完的方法岂不妙哉。<br>接下来的封装代码来自<code>《你不知道的JavaScript中卷》</code>一书中：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">run</span>(<span class="params">gen</span>)&#123;</span><br><span class="line">    <span class="keyword">var</span> args = [].<span class="property">slice</span>.<span class="title function_">call</span>(<span class="variable language_">arguments</span>,<span class="number">1</span>);</span><br><span class="line">    <span class="keyword">var</span> it;</span><br><span class="line">    <span class="comment">// 在当前上下文中初始化生成器</span></span><br><span class="line">    it = gen.<span class="title function_">apply</span>(<span class="variable language_">this</span>,args);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 返回一个Promise用于生成器完成</span></span><br><span class="line">    <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">resolve</span>()</span><br><span class="line">    .<span class="title function_">then</span>(<span class="keyword">function</span> <span class="title function_">handleNext</span>(<span class="params">value</span>)&#123;</span><br><span class="line">        <span class="comment">// 对于下一个yield出的值运行</span></span><br><span class="line">        <span class="keyword">var</span> next = it.<span class="title function_">next</span>(value);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 立即执行函数</span></span><br><span class="line">        <span class="keyword">return</span> (</span><br><span class="line">            <span class="keyword">function</span> <span class="title function_">handleResult</span>(<span class="params">next</span>)&#123;</span><br><span class="line">                <span class="comment">// 生成器运行完毕了吗？</span></span><br><span class="line">                <span class="keyword">if</span>(next.<span class="property">done</span>)&#123;</span><br><span class="line">                    <span class="keyword">return</span> next.<span class="property">value</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// 是否继续</span></span><br><span class="line">                <span class="keyword">else</span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">resolve</span>(next.<span class="property">value</span>)</span><br><span class="line">                    .<span class="title function_">then</span>(</span><br><span class="line">                        handleNext,</span><br><span class="line">                        <span class="keyword">function</span> <span class="title function_">handleErr</span>(<span class="params">err</span>)&#123;</span><br><span class="line">                            <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">resolve</span>(item.<span class="keyword">throw</span>(err))</span><br><span class="line">                            .<span class="title function_">then</span>(handleResult)</span><br><span class="line">                        &#125;</span><br><span class="line">                    )</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        )(next)</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过promise和generator函数封装就有了这个<code>run</code>这个工具。基本用法如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> *<span class="title function_">gen</span>(<span class="params"></span>)&#123;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">run</span>(gen)</span><br></pre></td></tr></table></figure>
<p>这样就会<code>自动异步运行Generator函数所生成的迭代器，直到结束</code>。  </p>
<blockquote>
<p>看起来也没什么了不起的呀？<br>接下来假设一个业务场景：<br>有request、request1、request2三个请求。但是需要request和request1这两个请求返回的数据作为request2请求参数发送到服务端。   </p>
</blockquote>
<p>下面是promise的实现方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">request</span>(<span class="params"></span>)&#123;</span><br><span class="line">   <span class="keyword">return</span> axios.<span class="title function_">get</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request1</span>(<span class="params"></span>)&#123;</span><br><span class="line">   <span class="keyword">return</span> axios.<span class="title function_">get</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request2</span>(<span class="params">data</span>)&#123;</span><br><span class="line">   <span class="keyword">return</span> axios.<span class="title function_">get</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>,&#123;<span class="attr">params</span>:data&#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">getData</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="title function_">request</span>().<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">data</span>)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(data); <span class="comment">// 打印返回结果</span></span><br><span class="line">        <span class="comment">// request1请求</span></span><br><span class="line">        <span class="title function_">request1</span>().<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">request1Data</span>)&#123;</span><br><span class="line">            <span class="comment">// request2请求</span></span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">request2</span>(&#123;<span class="attr">param</span>:data,<span class="attr">param1</span>:request1Data&#125;)</span><br><span class="line">        &#125;).<span class="title function_">then</span>(<span class="keyword">function</span>(<span class="params">allData</span>)&#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(allData)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;).<span class="title function_">catch</span>(<span class="keyword">function</span>(<span class="params">err</span>)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(err);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">getData</span>()</span><br></pre></td></tr></table></figure>
<p>promise确实是能实现的，但是有多个请求的情况并且下面的请求需要用到上面多个请求所返回的数据就会导致代码臃肿，可能造成回调地狱。</p>
<p>Generator函数搭配刚才的run工具就可以很好的解决这个问题。如：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">request</span>(<span class="params"></span>)&#123;</span><br><span class="line">   <span class="keyword">return</span> axios.<span class="title function_">get</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request1</span>(<span class="params"></span>)&#123;</span><br><span class="line">   <span class="keyword">return</span> axios.<span class="title function_">get</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">request2</span>(<span class="params">data</span>)&#123;</span><br><span class="line">   <span class="keyword">return</span> axios.<span class="title function_">get</span>(<span class="string">&#x27;http://xxx.com/xxx/xxx&#x27;</span>,&#123;<span class="attr">params</span>:data&#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span>* <span class="title function_">gen</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="keyword">const</span> res = <span class="keyword">yield</span> <span class="title function_">request</span>();</span><br><span class="line">    <span class="keyword">const</span> res1 = <span class="keyword">yield</span> <span class="title function_">request1</span>();</span><br><span class="line">    <span class="keyword">const</span> res2 = <span class="keyword">yield</span> <span class="title function_">request2</span>(&#123;</span><br><span class="line">        <span class="attr">param</span>:res,</span><br><span class="line">        <span class="attr">param1</span>:res</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(res2)</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">run</span>(gen)</span><br></pre></td></tr></table></figure>
<p>这样是不是一气呵成？<br>用过<a target="_blank" rel="noopener" href="https://dvajs.com/">dvajs</a>的应该已经看的出来了这个工具和dvajs的model中的effects使用方式是大同小异的。</p>
<h1 id="六、async、await和Generator函数的区别"><a href="#六、async、await和Generator函数的区别" class="headerlink" title="六、async、await和Generator函数的区别"></a>六、async、await和Generator函数的区别</h1><p>看到这里你可能看感觉很疑惑，感觉Generator函数的使用是并不多的，相反感觉刚才的那些业务场景async搭配await也能实现。<br>其实async和await就是Generator函数的语法糖，<code>async</code>相当于<code>*</code>，<code>await</code>相当于<code>yield</code>。</p>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关博客</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
        <div class="popular-posts-date">2020-03-21</div>
      <div class="popular-posts-title"><a href="js对象和数组之间相互转换/" rel="bookmark">js对象和数组之间相互转换</a></div>
      
    </li>
  </ul>


    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="/images/wechatpay.png" alt="wxb 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="/images/alipay.png" alt="wxb 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="followme">
  <span>欢迎关注我的其它发布渠道</span>

  <div class="social-list">

      <div class="social-item">
        <a target="_blank" class="social-link" href="/atom.xml">
          <span class="icon">
            <i class="fa fa-rss"></i>
          </span>

          <span class="label">RSS</span>
        </a>
      </div>
  </div>
</div>

          <div class="post-tags">
              <a href="/tags/ES6/" rel="tag"># ES6</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/antd%E4%B8%ADsetFieldsValue%E5%AF%BC%E8%87%B4%E6%8F%90%E7%A4%BA%E6%B6%88%E5%A4%B1/" rel="prev" title="antd中setFieldsValue导致提示消失">
                  <i class="fa fa-chevron-left"></i> antd中setFieldsValue导致提示消失
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/koa-static%E9%9D%99%E6%80%81%E6%89%98%E7%AE%A1/" rel="next" title="koa-static静态托管">
                  koa-static静态托管 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments gitalk-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wxb</span>
</div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <!-- <span id="busuanzi_value_site_uv"></span> -->
        <span id="uv-views"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <!-- <span id="busuanzi_value_site_pv"></span> -->
        <span id="pv-views"></span>
      </span>
    </span>
</div><script src="/js/diy_footer.js"></script>
  <div class="powered-by">
    <div style="display: inline-flex;align-items: center;">
      <img src="/images/copyrihgt.png" alt="wxb 微信" with='20' height='20' style="margin-right: 4px;">
      <a href="https://beian.miit.gov.cn/" target="_blank">浙ICP备2022027687号</a>
    </div>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/medium-zoom/1.0.6/medium-zoom.min.js" integrity="sha256-EdPgYcPk/IIrw7FYeuJQexva49pVRZNmt3LculEr7zM=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>




<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.7.2/gitalk.css" integrity="sha256-AJnUHL7dBv6PGaeyPQJcgQPDjt/Hn/PvYZde1iqfp8U=" crossorigin="anonymous">

<script class="next-config" data-name="gitalk" type="application/json">{"enable":true,"github_id":"dearDreamWeb","repo":"blogwxb.github.io","client_id":"86685a6104f8e6ba5827","client_secret":"7cf015e84bbe755bde20c8aca767977e316304ad","admin_user":"dearDreamWeb","distraction_free_mode":true,"proxy":"https://cors-anywhere.azm.workers.dev/https://github.com/login/oauth/access_token","language":"zh-CN","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/gitalk/1.7.2/gitalk.min.js","integrity":"sha256-Pmj85ojLaPOWwRtlMJwmezB/Qg8BzvJp5eTzvXaYAfA="},"path_md5":"302d15b84e753a9bdd893467b74cb821"}</script>
<script src="/js/third-party/comments/gitalk.js"></script>

</body>
</html>
